package m.jclecai.com.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import m.jclecai.com.R;
import m.jclecai.com.adapter.BetBjdcAdapter;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.dialog.BettingDialogFragment;
import m.jclecai.com.dialog.ShowOrderDialog;
import m.jclecai.com.listener.ISelectPlayListener;
import m.jclecai.com.listener.MyNotifyTextViewSetChanged;
import m.jclecai.com.utils.CalculateBetNums;
import m.jclecai.com.utils.MyToast;
import m.jclecai.com.utils.StringUtils;
import m.jclecai.com.utils.Utils;

import static m.jclecai.com.utils.CalculateBetNums.getBonus;
import static m.jclecai.com.utils.Utils.ZQ_ITEM_LIST;

public class BettingBJDCActivity extends BaseActivity implements MyNotifyTextViewSetChanged,View.OnClickListener,ISelectPlayListener {

    @BindView(R.id.tv_mid_title)
    TextView tv_mid_title;
    @BindView(R.id.rl_bar)
    RelativeLayout rl_bar;
    @BindView(R.id.include_term_stop_time)
    TextView include_term_stop_time;
    @BindView(R.id.include_listview)
    ListView include_listview;
    @BindView(R.id.include_bet_way)
    TextView include_bet_way;
    @BindView(R.id.include_multiple_context)
    EditText include_multiple_context;
    @BindView(R.id.toolbar_confirm)
    TextView toolbar_confirm;
    @BindView(R.id.tv_bonus)
    TextView tv_bonus;
    //注数
    int voteNums;
    //倍数
    String multiple;
    //是否有默认值要选中
    boolean check = true;
    //要选中的默认值过关方式
    private String pass="";
    //当前选中的过关方式 默认0为第一个
    private int currentDialoItemCheck = 0;
    BetBjdcAdapter adapter;
    //详情见arrays.xml 对应 jczq_types_list 用于ui区分
    int pager = 0;
    int buyMoney = 0;
    //奖金优化
    String vote,name;
    String termNo;

    @BindView(R.id.ll_bonus_optimize)
    View mLlBonusOptimizes;

    @BindView(R.id.cb_saidan)
    CheckBox mCbBox;
    private ShowOrderDialog mShowOrderDialog;
    private String mSlogan;
    private String mWrate;
    private String mSunOrderMode;


    @Override
    public int getContentView() {
        return R.layout.activity_betting_jczq;
    }


    @Override
    public void initView() {
        Intent intent = getIntent();
        pager = intent.getIntExtra("pager",0);
        name = intent.getStringExtra("name");
        termNo = intent.getStringExtra("termNo");
        setTitle(name);
        leftOptionText("添加");
        rightOptionText("发起合买");

        mShowOrderDialog = new ShowOrderDialog(this, new ShowOrderDialog.OnClickButtonListener() {

            @Override
            public void onClickSure(String mode, String profit, String slogan) {
                //确定;
                mSlogan = slogan;
                mWrate = profit;
                mSunOrderMode = mode;
            }

            @Override
            public void onClickCancel() {
                //取消；
                mCbBox.setChecked(false);
            }
        },"10","10");
    }

    @Override
    public void initData() {
        adapter = new BetBjdcAdapter(this,pager,this);
        View inflate = View.inflate(this,R.layout.lottery_list_footer,null);
        inflate.findViewById(R.id.betting_item_footer_clear).setOnClickListener(this);
        include_listview.addFooterView(inflate);
        //低版本 addFooterView需要在setAdapter前面
        include_listview.setAdapter(adapter);
        String[] names = getResources().getStringArray(R.array.lottery_pass_types_name_list);
        names = StringUtils.filterData(names,"串",Utils.ZQ_ITEM_LIST.size(),adapter.getCheckDan(),isDG());
        //默认选中的过关方式
        if(names != null && names.length>0){
            pass = names[names.length - 1];
        }else{
            pass="单关";
        }
        include_bet_way.setText(pass.replaceAll("1串1","单关"));
        getPredictBonus();
    }


    @OnClick(R.id.cb_saidan)
    void onClickShowOrder(){
        //这里表示点击的了显示跟单；
        mShowOrderDialog.show(buyMoney+"",(buyMoney/Integer.parseInt(multiple))+"");
    }


    //过关倍数
    @OnTextChanged(R.id.include_multiple_context)
    void multiple(Editable s){
        Log.e("bs",s.toString());
        if(TextUtils.isEmpty(include_multiple_context.getText().toString())){
            include_multiple_context.setText("1");
            return;
        }
        getPredictBonus();
    }

    //过关方式
    @OnClick(R.id.include_bet_way)
    void showPassType() {
        if(Utils.ZQ_ITEM_LIST.size() < 2 && !isDG()){
            MyToast.showToast(this,"至少选择2场比赛");
            return;
        }
        BettingDialogFragment dialogFragment = new BettingDialogFragment();
        dialogFragment.show(getSupportFragmentManager(), "Dialog");
        dialogFragment.setItemCount(Utils.ZQ_ITEM_LIST.size());
        dialogFragment.setMinCount(adapter.getCheckDan());
        dialogFragment.setListener(this);
        dialogFragment.setDG(isDG());
        dialogFragment.setDefCheck(check,pass,currentDialoItemCheck);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.betting_item_footer_clear:
                if(ZQ_ITEM_LIST.size() > 0)
                showAlertDialog("提示","确认清空所有数据?","取消","确认",null,new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ZQ_ITEM_LIST.clear();
                        adapter.notifyDataSetChanged();
                    }
                });
                break;
        }
    }

    //支付
    @OnClick(R.id.toolbar_confirm)
    void pay(){
        if(TextUtils.isEmpty(pass)){
            MyToast.showToast(getBaseContext(),"请选择过关方式");
            return;
        }
        /**
         * 此处提交之前先判断用户是否登录
         */
        String stringCode = StringUtils.getBonus(Utils.ZQ_ITEM_LIST,pass,false);
        Log.e("stringCode",stringCode);
        Intent intent = new Intent(this, LotteryPayActivity.class);
        intent.putExtra(PAY_VOTENUMS, String.valueOf(voteNums));
        intent.putExtra(PAY_MULTIPLE,multiple);
        intent.putExtra(PAY_MONEY, String.valueOf(buyMoney));
        intent.putExtra(PAY_CODES,stringCode);
        intent.putExtra(PAY_TYPE,"bjdc");
        intent.putExtra(PAY_PASS,pass.replaceAll("串","*").replaceAll("单关","1*1"));
        intent.putExtra(PAY_LOTTERY_TYPE,name);
        intent.putExtra(PAY_TERM,termNo);

        //这里是晒单的逻辑
        intent.putExtra(SUN_ORDER_MODE, mSunOrderMode);
        intent.putExtra(SUN_ORDER_SLOGAN, mSlogan);
        intent.putExtra(PAY_WRATE, mWrate);
        intent.putExtra(IS_SHOW_ORDER, mCbBox.isChecked()?"1":"0");

        startActivityForResult(intent, Constant_Result.CLOSEPAGE);
    }

    //奖金优化
    @OnClick(R.id.ll_bonus_optimize)
    void bonusOptimize(){
        if(TextUtils.isEmpty(pass)){
            MyToast.showToast(getBaseContext(),"请选择过关方式");
            return;
        }
        String stringCode = StringUtils.getBonusAward(Utils.ZQ_ITEM_LIST,pass,false);
        startActivityForResult(new Intent(this,BonusOptimizationActivity.class)
                .putExtra("codes",stringCode)
                .putExtra("vote",vote)
                .putExtra("pass",pass.replaceAll("串","*").replaceAll("单关","1*1"))
                .putExtra("money",buyMoney)
                .putExtra(PAY_LOTTERY_TYPE,name)
                .putExtra(PAY_MULTIPLE,multiple)
                .putExtra(PAY_VOTENUMS, String.valueOf(voteNums))
                .putExtra(PAY_TYPE,"bjdc")
                .putExtra(PAY_TYPE_NUM,getPlayType())
                .putExtra(PAY_TERM,getTerm())
        ,Constant_Result.CLOSEPAGE);
    }

    /**
     * 这里是获取期号；
     * @return
     */
    private String getTerm() {
        String term = getIntent().getStringExtra(PAY_TERM);
        return term;
    }




    private String getPlayType() {

    /*    <item>胜平负</item>
        <item>比分</item>
        <item>进球数</item>
        <item>半全场</item>
        <item>上下单双</item>*/
        if("胜平负".equals(name)){

            return "61";

        }else if("比分".equals(name)){

            return "63";

        }else if("进球数".equals(name)){

            return "62";

        }else if("半全场".equals(name)){

            return "64";

        }else if("上下单双".equals(name)){
            //这里；
            return "65";
        }

        return "61";
    }

    /**
     * 预测奖金
     */
    private void getPredictBonus() {
        if(Utils.ZQ_ITEM_LIST.size() < 2 && !isDG()){
            MyToast.showToast(this,"至少选择2场比赛");
            tv_bonus.setText("");
            include_bet_way.setText("过关方式");
            this.pass = "";
            return;
        }
        //算预测奖金
        try{
            vote = StringUtils.getBonusCode(Utils.ZQ_ITEM_LIST);
            Log.e("getBonusCode",vote);
            if(TextUtils.isEmpty(vote) || TextUtils.isEmpty(pass)){
                MyToast.showToast(getBaseContext(),"请选择过关方式");
                return;
            }
            String buyType = pass.replaceAll("串","*");
            buyType = buyType.replaceAll("单关","1*1");
            CalculateBetNums calculateBetNums = new CalculateBetNums();
            //得到的是注数
            voteNums = calculateBetNums.getVoteNums(vote, buyType);
            List<String> rebuildVote = CalculateBetNums.rebuildVote(vote, buyType);
            String sp_max = getBonus(rebuildVote, 1, 1);//最大奖金
            String sp_min = getBonus(rebuildVote, 0, 1);//最小奖金
            multiple = include_multiple_context.getText().toString().trim();
            int num = Integer.parseInt(multiple);
            String money = (num * Float.parseFloat(sp_min)) + "~" + (num * Float.parseFloat(sp_max));
            buyMoney = (voteNums * num * 2);
            String txt = String.format(getString(R.string.jc_bonus_optimiiza),voteNums,num,buyMoney,money);
            tv_bonus.setText(Html.fromHtml(txt));

        }catch (Exception e){
            MyToast.showToast(getBaseContext(),"计算异常");
            e.printStackTrace();
        }
    }

    //支持单关的小蓝点
    boolean isDG(){
        return true;
    }

    @Override
    public void onClickSetChangedText() {
        tv_bonus.setText("");
        include_bet_way.setText("过关方式");
        this.pass = "";
        adapter.notifyDataSetChanged();
    }

    @Override
    public void refreshData() {
        tv_bonus.setText("");
        include_bet_way.setText("过关方式");
        this.pass = "";
        adapter.notifyDataSetChanged();
    }

    @Override
    public void select(String value, int itemPosition) {
        currentDialoItemCheck = itemPosition;
        this.pass = value;
        check = !TextUtils.isEmpty(value);
        if (TextUtils.isEmpty(value)) {
            include_bet_way.setText("过关方式");
            tv_bonus.setText("");
        } else{
            include_bet_way.setText(value.replaceAll("1串1", "单关")
                    .replaceAll("[*]", "串"));
        }
        getPredictBonus();
    }

    //合买
    @OnClick(R.id.tv_right_option)
    void jointPurchase() {


        new AlertDialog.Builder(this)
                .setMessage("功能开发中...")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();

/*        if(Utils.ZQ_ITEM_LIST.size() < 2 && !isDG()){
            MyToast.showToast(this,"至少选择2场比赛");
            tv_bonus.setText("");
            include_bet_way.setText("过关方式");
            this.pass = "";
            return;
        }
        if(TextUtils.isEmpty(vote) || TextUtils.isEmpty(pass)){
            MyToast.showToast(getBaseContext(),"请选择过关方式");
            return;
        }
        String stringCode = StringUtils.getBonus(Utils.ZQ_ITEM_LIST,pass,pager == 2);
        Intent intent = new Intent(this, JointPurchaseActivity.class);
        intent.putExtra("totalNum",voteNums);
        intent.putExtra("multiple", Integer.valueOf(multiple));
        intent.putExtra("totalMoney", buyMoney);
        intent.putExtra("num", 1);
        intent.putExtra(PAY_TYPE, "bjdc");
        intent.putExtra(PAY_CODES, stringCode+";");//因为JointPurchaseActivity code会-1
        intent.putExtra(PAY_NAME, "合买");
        startActivityForResult(intent,Constant_Result.CLOSEPAGE);*/
    }

    @Override
    protected void close(){
        finish();
    }
}
